package com.rory.gooday.task;

import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Page;
import com.rory.gooday.common.R;
import com.rory.gooday.common.model.Task;

@Path("/task")
public class TaskController extends Controller {
	
	@Inject
	TaskService service;
	
	public void index() {
		render("task.html");
	}

	public void data() {
		Page<Task> a =  service.paginate(getParaToInt("page", 1), getParaToInt("limit", 10));
		renderJson(R.ok(a));
	}
	
	public void add() {
	}
	
	/**
	 * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
	 * 并要对数据进正确性进行验证，在此仅为了偷懒
	 */
//	@Before(BlogValidator.class)
	public void save() {
        Task task = getBean(Task.class);
        String isMsg=getPara("isMsg");
        String isArchiv = getPara("isArchiv");
        task.setIsMsg(isMsg);
        task.setIsArchiv(isArchiv);
        task.setCtime(new java.util.Date());
        renderJson(R.ok(task.save()));
	}
	
	public void edit() {
		Task a = service.findById(getParaToInt());
		setAttr("task", a);
	}
	
	/**
	 * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
	 * 并要对数据进正确性进行验证，在此仅为了偷懒
	 */
//	@Before(BlogValidator.class)
	public void update() {
        Task task = getBean(Task.class);
        String isMsg=getPara("isMsg");
        String isArchiv = getPara("isArchiv");
        task.setIsMsg(isMsg);
        task.setIsArchiv(isArchiv);
        renderJson(R.ok(task.update()));
	}
	
	public void delete() {
		service.deleteById(getParaToInt());
		redirect("/task");
	}

    public void updateField() {
        String field = getPara("field");
        String value = getPara("value");
        int id = getParaToInt("id");
        Task task = service.findById(id);
        if (task != null){
            switch (field){
                case "task_title":
                    task.setTaskTitle(value);
                    break;
                case "note":
                    task.setNote(value);
                    break;
                case "feedback_note":
                    task.setFeedbackNote(value);
                    break;
                case "feedback_man":
                    task.setFeedbackMan( value);
                    break;
                default:
                    break;
            }
            task.update();
            renderJson(R.ok());
        }
    }
}


